/*
 * Created on Jun 1, 2005 TODO To change the template for this generated file go
 * to Window - Preferences - Java - Code Style - Code Templates
 */
package com.novix.utility.web;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import lotus.domino.NotesException;
import lotus.domino.NotesFactory;
import lotus.domino.Session;

import org.apache.log4j.Logger;

import com.novix.portal.framework.dao.DAOFactory;
import com.novix.portal.framework.dao.IWebContactDAO;
import com.novix.portal.framework.dao.IWebOrganizationDAO;
import com.novix.portal.framework.util.IConstants;
import com.opensymphony.oscache.base.NeedsRefreshException;
import com.opensymphony.oscache.general.GeneralCacheAdministrator;

/**
 * @author Dev TODO To change the template for this generated type comment go to Window - Preferences - Java - Code
 *         Style - Code Templates
 */
public class CacheLoader extends HttpServlet {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(CacheLoader.class);

    /**
     * Constructor of the object.
     */
    public CacheLoader() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * Initialization of the servlet. <br>
     * 
     * @throws ServletException
     *             if an error occure
     */
    public void init() throws ServletException {
        Session session = null;
        String corbaServerName = getServletContext().getInitParameter(IConstants.DOMINO_DIIOP_SERVER_NAME);
        String serverName = getServletContext().getInitParameter(IConstants.DOMINO_SERVER);
        String adminName = Messages.getString("CacheLoader.name"); //$NON-NLS-1$
        String adminPassword = Messages.getString("CacheLoader.password"); //$NON-NLS-1$
        String iePath = getServletContext().getInitParameter(IConstants.IEXTENSIONS_PATH);
        try {
            if (getServletContext().getInitParameter(IConstants.USE_CACHE_LOADER) != null
                    && getServletContext().getInitParameter(IConstants.USE_CACHE_LOADER).compareToIgnoreCase("TRUE") == 0) {
                GeneralCacheAdministrator admin = new GeneralCacheAdministrator();

                session = NotesFactory.createSession(corbaServerName, adminName, adminPassword);

                DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.DOMINO);

                IWebOrganizationDAO dao = factory.getWebOrganizationDAO();
                List list = dao.selectAllWebOrganizations(session, serverName, iePath);
                // getServletContext().setAttribute(IConstants.WEB_ORGANIZATION_CACHE,
                // list);
                admin.putInCache(IConstants.WEB_ORGANIZATION_CACHE, list);

                IWebContactDAO webContactDao = factory.getWebContactDAO();
                List contactList = webContactDao.selectAllWebContacts(session, serverName, iePath);
                // getServletContext().setAttribute(IConstants.WEB_CONTACTS_CACHE,
                // contactList);
                admin.putInCache(IConstants.WEB_CONTACTS_CACHE, contactList);
                getServletContext().setAttribute(IConstants.OS_CACHE_ADMIN, admin);

                List contactListAllPicsOrNo = webContactDao.selectAllWebContactsPicsOrNone(session, serverName, iePath);
                // getServletContext().setAttribute(IConstants.WEB_CONTACTS_CACHE,
                // contactList);
                admin.putInCache(IConstants.WEB_CONTACTS_PICS_OR_NO_CACHE, contactListAllPicsOrNo);
                getServletContext().setAttribute(IConstants.OS_CACHE_ADMIN, admin);

                TimerTask cacheCleaner = new CacheCleaner(getServletContext(), admin, corbaServerName, adminName,
                        adminPassword, serverName, iePath);
                // perform the task once a day at 1 a.m.
                Timer timer = new Timer();
                timer.scheduleAtFixedRate(cacheCleaner, getTomorrowMorning1am(), fDailyOccurenceInMilliseconds);
                admin.putInCache(IConstants.CACHE_CLEANER, cacheCleaner);
                // timer.scheduleAtFixedRate(cacheCleaner, new Date(System.currentTimeMillis()+300000), 300000);
                if (logger.isInfoEnabled())
                    logger.info("successfully regenerated cache for orgs and contacts");
                logger.error("successfully regenerated cache for orgs and contacts");
            }

        } catch (NotesException e) {
            logger.error(e);
        } finally {
            try {
                if (session != null && session.isValid())
                    session.recycle();
            } catch (NotesException e) {
                logger.error(e);
            }
        }

    }

    // expressed in milliseconds
    //this is every 2 hours
    private final static long fDailyOccurenceInMilliseconds = 1000 * 60 * 60 * 2;

    private final static int fONE_DAY = 1;

    private final static int fHourToStart = 5;

    private final static int fZERO_MINUTES = 0;

    private static Date getTomorrowMorning1am() {
        Calendar tomorrow = new GregorianCalendar();
        tomorrow.add(Calendar.DATE, fONE_DAY);
        Calendar result = new GregorianCalendar(tomorrow.get(Calendar.YEAR), tomorrow.get(Calendar.MONTH), tomorrow
                .get(Calendar.DATE), fHourToStart, fZERO_MINUTES);
        return result.getTime();
    }

}
